package Parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XMLParser {

	String XMLFileURI;
	List nodes, edges, nodesAndEdges;
	Document dom;
	
	public XMLParser(){
		nodes = new ArrayList();
		edges = new ArrayList();
		nodesAndEdges = new ArrayList();
	}
	
	public List parse(String fileToParse){
		List ret = new ArrayList();
		
		XMLFileURI = fileToParse;
		
		parseXMLFile();
		
		parseDocument();
		
		nodesAndEdges.add(nodes);
		nodesAndEdges.add(edges);
		ret = nodesAndEdges;
			
		return ret;
	}
	
	private void parseXMLFile(){
		//generate a new DocumentBuilderFactory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try {
			
			//use the factory to get a DocumentBuilder
			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse the file with the DocumentBuilder and generate a new parsed Document
			dom = db.parse(XMLFileURI);

		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	private void parseDocument(){
		//get the root Element
		Element docEle = dom.getDocumentElement();
		
		//get a NodeList of Node Elements
		NodeList allNodesList = docEle.getElementsByTagName("node");
		
		if(allNodesList != null && allNodesList.getLength() > 0) {
			for(int i = 0 ; i < allNodesList.getLength();i++) {
				
				//get a node from the list, as an element
				Element el = (Element)allNodesList.item(i);
				
				//build the Node object
				Node e = this.getNodeParent(el);
				
				//add it to the list
				nodes.add(e);
			}
		}	
		
		NodeList allEdgesList = docEle.getElementsByTagName("edge");
		
		if(allEdgesList != null && allEdgesList.getLength() > 0) {
			for(int i = 0 ; i < allEdgesList.getLength();i++) {
				
				//get the employee element
				Element el = (Element)allEdgesList.item(i);
				
				//build the Node object
				Edge e = this.getEdgeParent(el);
				
				//add it to the list
				edges.add(e);
			}
		}
	}
	
	private Node getNodeParent(Element iel){		
		String id = iel.getAttribute("id");
		
		Node ret = new Node(id);
		
		return ret;
	}
	
	private Edge getEdgeParent(Element iel){		
		String source = iel.getAttribute("source");
		String target = iel.getAttribute("target");
		
		Edge ret = new Edge(source, target);
		
		return ret;
	}
}
